// 公共函数
import * as fs from 'fs'
import * as path from 'path'
import { Router } from 'express'
const router = Router()

/**
 * 正确结果 code = 200
 * @param data 需要返回的数据
 * @param msg 返回提示
 */
export const Succeed = (data: any, msg: string = '获取成功') => {
	return {
		code: 200,
		msg,
		data
	}
}

/**
 * md5 加密
 * @type string
 * @param stj 传入需要加密的账号或者是密码
 */
export function md5s(stj: string) {
	const crypto = require('crypto')
	const md5 = crypto.createHash('md5')
	md5.update(stj)
	stj = md5.digest('hex')
	console.log('stj > ', stj)
	return stj
}

const authMiddleware = (back: any) => {
	return (req: any, res: any) => {
		const authorize = back.authorize
		if (authorize && typeof authorize === 'function') {
			return authorize.call(null, req, res)
		}
		return res()
	}
}

export const Get = (path: string) => {
	return (context: any, key: string) => {
		const controller = context[key]
		router.get(path, authMiddleware(controller), controller)
	}
}

export const Post = (path: string) => {
	return (context: any, key: string) => {
		const controller = context[key]
		router.post(path, authMiddleware(controller), controller)
	}
}

export class Exception extends Error {
	private code: number
	private msg: string

	constructor(code: number, msg: string = '获取成功') {
		super(msg)
		this.code = code
		this.msg = msg
	}

	get statusCode(): number {
		return this.code
	}

	public toObject(): Object {
		return {
			code: this.code,
			msg: this.msg
		}
	}
}
